<?php
/**
 * Created by JetBrains PhpStorm.
 * User: miaodb
 * Date: 11-10-8
 * Time: 下午2:28
 * To change this template use File | Settings | File Templates.
 */
 
class CLI_Update2java extends CLI
{


    /**
     * 脚本主方法
     *
     * @return void
     */
    public function main()
    {
        $this->create_account();
    }

    public function create_account(){
        //创建会员虚拟账户
        cli::output("开始创建虚拟账户\n");
        $select = DB::select()->from("members");
        $iterator = new Db_Iterator($select, 'default', 10);
        $i = 0;
        while ($iterator->valid())
        {
            // 遍历数据
			foreach ($iterator->current() as $member)
            {
                if(!$member['nickname'])continue;
                $tc_account = DB::select()->from("tc_account")->where('member_id', '=', $member['member_id'])->fetch_row();

                if (empty($tc_account)) {
                    //不存在就创建
                    $data = array(
                        'member_id' => $member['member_id'],
                        'nickname' => $member['nickname'],
                        'email' => $member['email'],
                        'type' => $member['member_type']==1?0:1,
                        'total' => 0,
                        'status' => !$member['locked'],
                        'flag' => 0,
                        'created' => time(),
                    );

                    DB::insert('tc_account', array_keys($data))->values(array_values($data))->execute();
                   
                    $i++;
                }
                elseif($tc_account['nickname']!=$member['nickname'])
                {
                    $update = array('nickname'=>$member['nickname']);
                    DB::update('tc_account')->set($update)->where('member_id','=',$member['member_id'])->execute();
                }

            }
            echo '>';
            $iterator->next();
        }
        cli::output("\n成功创建{$i}个虚拟账户");
        return $this;
    }

    public function create_item_trade(){
        //转换交易记录
        cli::output("开始创建交易记录\n");
        $select = DB::select()->from("order_trades");
        $iterator = new Db_Iterator($select, 'default', 10);
        $i = 0;
        while ($iterator->valid())
        {
            // 遍历数据
			foreach ($iterator->current() as $item_trade)
            {
                //不存在就创建
                $data = array(
                    'item_id' => $item_trade['goods_id'],
                    'nickname' => $item_trade['nickname'],
                    'item_title' => $item_trade['goods_title'],
                    'prop_str' => $item_trade['prop_str']?$item_trade['prop_str']:'',
                    'original_price' => $item_trade['original_price'],
                    'price' => $item_trade['price'],
                    'quantity' => $item_trade['quantity'],
                    'is_anonymity' => $item_trade['is_anonymity'],
                    'source' => $item_trade['source'],
                    'created' => time(),
                    'sys' => $item_trade['sys'],
                );

                DB::insert('tc_item_trade', array_keys($data))->values(array_values($data))->execute();

                $i++;
            }
            echo '>';
            $iterator->next();
        }

        cli::output("\n成功创建{$i}个交易记录");
        return $this;
    }

    public function create_log(){
        //插入交易日志
        cli::output("开始创建交易日志\n");
        $select = DB::select()->from("order_logs");
        $iterator = new Db_Iterator($select, 'default', 10);
        $i = 0;
        while ($iterator->valid())
        {
            // 遍历数据
			foreach ($iterator->current() as $logs)
            {
                //不存在就创建
                $data = array(
                    'trade_sn' => $logs['order_id'],
                    'operater' => DB::select('nickname')->from('members')->where('member_id','=',$logs['member_id'])->fetch_one(),
                    'notes' => $logs['notes'],
                    'ip' => $logs['ip'],
                    'log_time' => $logs['log_time'],

                );

                DB::insert('tc_trade_log', array_keys($data))->values(array_values($data))->execute();

                $i++;
            }
            echo '>';
            $iterator->next();
        }

        cli::output("\n成功创建{$i}个交易日志");
        return $this;
    }

    public function create_trade_unpay()
    {
        //插入交易日志
        cli::output("开始创建未付款订单\n");
        $select = DB::select()->from("orders")->where('money_paid', '=', 0);
        $iterator = new Db_Iterator($select, 'default', 10);
        $i = $filter_count = 0;
        while ($iterator->valid())
        {
            // 遍历数据
			foreach ($iterator->current() as $order)
            {
                $order_goods = DB::select()->from('order_goods')->where('order_id', '=', $order['order_id'])->fetch_all();
                if(count($order_goods) == 0){
                    echo "\n忽略订单id:".$order['order_id']."\n";
                    $filter_count++;
                    continue;
                }
                $shop = DB::select()->from('shops')->where('shop_id', '=', $order['shop_id'])->fetch_row();
                $seller_nick = DB::select('nickname')->from('members')->where('member_id', '=', $shop['member_id'])->fetch_one();
                $buyer_nick = DB::select('nickname')->from('members')->where('member_id', '=', $order['member_id'])->fetch_one();
                if(empty($shop) or empty($seller_nick) or empty($buyer_nick)){
                    echo "\n忽略订单id:".$order['order_id']."\n";
                    $filter_count++;
                    continue;
                }

                //获得促销获得id
                $activity_id = 0;
                if(isset($order_goods[0]) and $order_goods[0]['snapshot'] and $order_goods[0]['source']!='NORMAL'){
                    $snapshot = @unserialize($order_goods[0]);
                    if (isset($snapshot['source_id'])) {
                        $activity_id = (int)$snapshot['source_id'];
                    }
                }

                //ip地址
                $ip = DB::select('ip')->from('order_logs')->where('order_id', '=', $order['order_sn'])->where('notes', 'in', array('[创建订单]', '[快速购买创建订单]'))->fetch_one();

                //运输方式
                $ship_type = $order['freight_type']=='SELF'?'FREE':$order['freight_type'];

                //插入tc_trade表记录
                $data = array(
                    'trade_sn' => $order['order_sn'],
                    'pay_sn' => $order['pay_order_sn'],
                    'shop_id' => $order['shop_id'],
                    'title' => $shop['shop_name'],
                    'buyer_message' => $order['buyer_words'],
                    'buyer_memo' => $order['buyer_memo'],
                    'seller_memo' => $order['seller_memo'],
                    'trade_memo' => $order['trade_memo'],
                    'trade_from' => $order_goods[0]['source'],
                    'seller_nick' => $seller_nick,
                    'buyer_nick' => $buyer_nick,
                    'trade_no' => $order['payment_no'],
                    'alipay_url' => '',
                    'ip' => $ip,
                    'activity_id' => $activity_id,
                    'timeout_action_time' => (int)$order['timeout'],
                    'status' => $order['order_status'],
                    'pay_time' => (int)$order['pay_time'],
                    'end_time' => (int)$order['end_time'],
                    'ship_time' => (int)$order['ship_time'],
                    'ship_type' => $ship_type,
                    'ship_no' => $order['ship_no'],
                    'ship_company' => $order['express'],
                    'ship_fee' => (int)$order['ship_fee'],
                    'ship_status' => $order['ship_no']?'SHIPPED':'NO_SHIPPED',
                    'trade_fee' => $order['order_amount'],
                    'discount_fee' => abs($order['discount_fee']),
                    'refund_fee' => 0.00,
                    'payment' => 0.00,
                    'is_anonymity' => $order['is_anonymity'],
                    'buyer_rate' => $order['buyer_rate'],
                    'seller_rate' => $order['seller_rate'],
                    'modified' => (int)$order['modified'],
                    'created' => $order['created'],
                    'available_cash' => 0.00,
                    'buyer_hide' => $order['buyer_hide'],
                    'seller_hide' => $order['seller_hide'],
                    'buyer_last_remind' => $order['buyer_last_remind'],
                    'seller_last_remind' => $order['seller_last_remind'],
                    'is_delay' => $order['is_delay'],
                    'selected_pay' => $order['bank_selected'],
                    'last_click_pay_button' => $order['last_paytime'],
                    'pay_type' => 'ALIPAY',
                    'flag' => '',
                );

                $trade = DB::insert('tc_trade', array_keys($data))->values(array_values($data))->execute();

                //插入收货地址
                $address = DB::select()->from('order_ships')->where('order_id', '=', $order['order_id'])->fetch_row();
                if($address)
                {
                    $data = array(
                        'trade_id'=>$trade[0],
                        'receiver_name'=>$address['consignee'],
                        'phone'=>$address['phone'],
                        'mobile'=>$address['mobile'],
                        'zip'=>$address['postalcode'],
                        'province'=>$address['province']?$address['province']:'',
                        'address'=>$address['address'],
                        'city'=>$address['city']?$address['city']:'',
                        'district'=>$address['district']?$address['district']:'',
                        'created'=>time(),
                    );
                    DB::insert('tc_trade_address', array_keys($data))->values(array_values($data))->execute();

                }

                //插入tc_order表记录
                $is_first = 1;
                $parent_id = 0;
                foreach($order_goods as $goods)
                {
                    $sku_id = 0;
                    if($goods['prop_str'])
                    {
                        $sku_id = (int)DB::select('sku_id')->from('item_skus')->where('goods_id', '=', $goods['goods_id'])->where('prop_str', '=', $goods['prop_str'])->fetch_one();
                    }

                    $ship_fee = 0;
                    if($is_first)
                    {
                        $ship_fee = $order['ship_fee'];
                    }

                    $data = array(
                        'trade_id'=>$trade[0],
                        'item_id'=>$goods['goods_id'],
                        'sku_id'=>$sku_id,
                        'cid'=>(int)$goods['cid'],
                        'title'=>$goods['goods_title'],
                        'price'=>$goods['price'],
                        'retail_price'=>$goods['original_price'],
                        'image_md5'=>$goods['image_md5'],
                        'protection_str'=>$shop['protections'],
                        'num'=>$goods['quantity'],
                        'seller_nick'=>$seller_nick,
                        'buyer_nick'=>$buyer_nick,
                        'props_str'=>$goods['prop_str'],
                        'refund_id'=>0,
                        'refund_status'=>'NO_REFUND',
                        'timeout_action_time'=>(int)$goods['timeout'],
                        'status'=>$goods['status']=='WAIT_BUYER_PAY'?'WAIT_BUYER_PAY':'TRADE_CLOSED',
                        'coupon_name'=>$goods['promotion_name'],
                        'discount_fee'=>abs($goods['discount_fee']),
                        'adjust_fee'=>'-'.$goods['adjust_fee'],
                        'ship_fee'=>$ship_fee,
                        'total_fee'=>$goods['amount']+$goods['adjust_fee'],
                        'modified'=>(int)$goods['modified'],
                        'created'=>$goods['created'],
                    );

                    $insert = DB::insert('tc_order', array_keys($data))->values(array_values($data))->execute();

                    //更新parent_id
                    if($is_first){
                        $parent_id = $insert[0];
                    }
                    $update = array('parent_id' => $parent_id);
                    DB::update('tc_order')->set($update)->where('id','=',$insert[0])->execute();
                    $is_first = 0;

                    $this->create_snapshot($goods['goods_id'], $insert[0]);

                }

                $i++;
            }
            echo '>';
            $iterator->next();
        }

        cli::output("\n成功创建{$i}个未付款订单,忽略{$filter_count}个订单");
        return $this;
    }


    public function create_trade_paid(){
        //插入交易日志
        cli::output("开始创建已付款订单\n");
        $select = DB::select()->from("orders")->where('money_paid', '!=', 0);
        $iterator = new Db_Iterator($select, 'default', 10);
        $i = 0;
        $filter_count = 0;
        while ($iterator->valid())
        {
            // 遍历数据
			// 遍历数据
			foreach ($iterator->current() as $order)
            {
                $order_goods = DB::select()->from('order_goods')->where('order_id', '=', $order['order_id'])->fetch_all();
                if(count($order_goods) == 0){
                    echo "\n忽略订单id:".$order['order_id']."\n";
                    $filter_count++;
                    continue;
                }
                $shop = DB::select()->from('shops')->where('shop_id', '=', $order['shop_id'])->fetch_row();
                $seller_nick = DB::select('nickname')->from('members')->where('member_id', '=', $shop['member_id'])->fetch_one();
                $buyer = DB::select()->from('members')->where('member_id', '=', $order['member_id'])->fetch_row();
                $buyer_nick = $buyer['nickname'];
                if(empty($shop) or empty($seller_nick) or empty($buyer_nick)){
                    echo "\n忽略订单id:".$order['order_id']."\n";
                    $filter_count++;
                    continue;
                }
                //获得促销获得id
                $activity_id = 0;
                if($order_goods[0]['snapshot'] and $order_goods[0]['source']!='NORMAL'){
                    $snapshot = @unserialize($order_goods[0]);
                    if (isset($snapshot['source_id'])) {
                        $activity_id = (int)$snapshot['source_id'];
                    }
                }

                //ip地址
                $ip = DB::select('ip')->from('order_logs')->where('order_id', '=', $order['order_sn'])->where('notes', 'in', array('[创建订单]', '[快速购买创建订单]'))->fetch_one();

                //运输方式
                $ship_type = $order['freight_type']=='SELF'?'FREE':$order['freight_type'];

                //插入tc_trade表记录
                $data = array(
                    'trade_sn' => $order['order_sn'],
                    'pay_sn' => $order['pay_order_sn'],
                    'shop_id' => $order['shop_id'],
                    'title' => $shop['shop_name'],
                    'buyer_message' => $order['buyer_words'],
                    'buyer_memo' => $order['buyer_memo'],
                    'seller_memo' => $order['seller_memo'],
                    'trade_memo' => $order['trade_memo'],
                    'trade_from' => $order_goods[0]['source'],
                    'seller_nick' => $seller_nick,
                    'buyer_nick' => $buyer_nick,
                    'trade_no' => $order['payment_no'],
                    'alipay_url' => '',
                    'ip' => $ip,
                    'activity_id' => $activity_id,
                    'timeout_action_time' => (int)$order['timeout'],
                    'status' => $order['order_status'],
                    'pay_time' => (int)$order['pay_time'],
                    'end_time' => (int)$order['end_time'],
                    'ship_time' => (int)$order['ship_time'],
                    'ship_type' => $ship_type,
                    'ship_no' => $order['ship_no'],
                    'ship_company' => $order['express'],
                    'ship_fee' => (float)$order['ship_fee'],
                    'ship_status' => $order['ship_no']?'SHIPPED':'NO_SHIPPED',
                    'trade_fee' => $order['order_amount'],
                    'discount_fee' => abs($order['discount_fee']),
                    'refund_fee' => $order['refund_amount'],
                    'payment' => $order['money_paid'],
                    'is_anonymity' => $order['is_anonymity'],
                    'buyer_rate' => $order['buyer_rate'],
                    'seller_rate' => $order['seller_rate'],
                    'modified' => (int)$order['modified'],
                    'created' => $order['created'],
                    'available_cash' => $order['receive_amount'],
                    'buyer_hide' => $order['buyer_hide'],
                    'seller_hide' => $order['seller_hide'],
                    'buyer_last_remind' => $order['buyer_last_remind'],
                    'seller_last_remind' => $order['seller_last_remind'],
                    'is_delay' => $order['is_delay'],
                    'selected_pay' => $order['bank_selected'],
                    'last_click_pay_button' => $order['last_paytime'],
                    'pay_type' => 'ALIPAY',
                    'flag' => '',
                );

                $trade = DB::insert('tc_trade', array_keys($data))->values(array_values($data))->execute();

                //创建付款记录
                if($order['hand_pay'])
                {
                    //手动付款，插入tc_hand_pay_log
                    $data = array(
                        'trade_sn'=>$order['order_sn'],
                        'operater'=>'超级管理员',
                        'pay_fee'=>$order['money_paid']?$order['money_paid']:$order['order_amount'],
                        'pay_memo'=>$order['order_amount'],
                        'created'=>time(),
                    );
                    DB::insert('tc_hand_pay_log', array_keys($data))->values(array_values($data))->execute();
                }
                elseif($order['payment_no'])
                {
                    //支付宝付款,插入tc_alipay_notify
                    //判断是否有合并付款的记录
                    $is_exist = DB::select()->from('tc_alipay_notify')->where('trade_no', '=', $order['payment_no'])->count_all();
                    if (!$is_exist) {
                        $money_paid_total = DB::select(DB::expr('sum(money_paid)'))->from('orders')->where('payment_no', '=', $order['payment_no'])->fetch_one();
                        $data = array(
                            'buyer_email'=>$buyer['email'],
                            'buyer_id'=>$buyer['member_id'],
                            'out_trade_no'=>$order['pay_order_sn'],
                            'total_fee'=>$money_paid_total,
                            'trade_no'=>$order['payment_no'],
                            'extra_common_param'=>$buyer['nickname'],
                            'created'=>$order['pay_time']?$order['pay_time']:time(),
                        );

                        DB::insert('tc_alipay_notify', array_keys($data))->values(array_values($data))->execute();

                    }
                }

                $buyer_account_id = DB::select('id')->from('tc_account')->where('nickname', '=', $buyer_nick)->fetch_one();

                //创建账户金额详情,收入
                $data = array(
                    'account_id'=>$buyer_account_id,
                    'trade_id'=>$trade[0],
                    'refund_id'=>0,
                    'amount'=>$order['money_paid']?$order['money_paid']:$order['order_amount'],
                    'flag'=>1,
                    'type'=>$order['hand_pay']?'HAND_PAY':'ALI_PAY',
                    'created'=>$order['pay_time']?$order['pay_time']:time(),
                );
                DB::insert('tc_account_detail', array_keys($data))->values(array_values($data))->execute();


                //创建账户金额详情,付款成功，支出
                $data = array(
                    'account_id'=>$buyer_account_id,
                    'trade_id'=>$trade[0],
                    'refund_id'=>0,
                    'amount'=>$order['money_paid']?$order['money_paid']:$order['order_amount'],
                    'flag'=>0,
                    'type'=>'TRADE_PAID',
                    'created'=>$order['pay_time']?$order['pay_time']:time(),
                );
                DB::insert('tc_account_detail', array_keys($data))->values(array_values($data))->execute();

                if($order['order_status'] == 'TRADE_FINISHED' and $order['receive_amount']){
                    //确认收货，交易完成,插入tc_account_detail
                    $seller_account_id = DB::select('id')->from('tc_account')->where('nickname', '=', $seller_nick)->fetch_one();
                    $data = array(
                        'account_id'=>$seller_account_id,
                        'trade_id'=>$trade[0],
                        'refund_id'=>0,
                        'amount'=>$order['receive_amount'],
                        'flag'=>1,
                        'type'=>'TRADE_FINISHED',
                        'created'=>$order['end_time']?$order['end_time']:time(),
                    );
                    DB::insert('tc_account_detail', array_keys($data))->values(array_values($data))->execute();

                    //如果在旧版的财务系统没有结算则更新商家账户余额，在新版的财务系统结算
                    $is_checked = DB::select()->from('fin_orders')->where('order_sn', '=', $order['order_sn'])->where('status', '=', 2)->count_all();
                    if (!$is_checked) {
                        $update = array('total'=>DB::expr('total'+$order['receive_amount']));
                        DB::update('tc_account')->set($update)->where('id', '=', $seller_account_id)->execute();
                    }
                }


                if($order['refund_amount']){
                    //存在退款金额，还没结算，在新版中给买家结算,增加虚拟账户金额
                    $is_checked = DB::select()
                            ->from('fin_balance_items')
                            ->join("fin_balances")
                            ->on('fin_balance_items.balance_id','=','fin_balances.balance_id')
                            ->where('fin_balance_items.order_sn','=',$order['order_sn'])
                            ->where('fin_balances.status','=', 3)
                            ->count_all();
                    if (!$is_checked) {
                        $update = array('total'=>DB::expr('total'+$order['refund_amount']));
                        DB::update('tc_account')->set($update)->where('id', '=', $buyer_account_id)->execute();

                    }
                }

                //插入收货地址
                $address = DB::select()->from('order_ships')->where('order_id', '=', $order['order_id'])->fetch_row();
                if($address)
                {
                    $data = array(
                        'trade_id'=>$trade[0],
                        'receiver_name'=>$address['consignee'],
                        'phone'=>$address['phone'],
                        'mobile'=>$address['mobile'],
                        'zip'=>$address['postalcode'],
                        'province'=>$address['province']?$address['province']:'',
                        'address'=>$address['address'],
                        'city'=>$address['city']?$address['city']:'',
                        'district'=>$address['district']?$address['district']:'',
                        'created'=>time(),
                    );
                    DB::insert('tc_trade_address', array_keys($data))->values(array_values($data))->execute();

                }

                //插入tc_order表记录
                $is_first = 1;
                $parent_id = 0;
                foreach($order_goods as $goods)
                {
                    $sku_id = 0;
                    if($goods['prop_str'])
                    {
                        $sku_id = (int)DB::select('sku_id')->from('item_skus')->where('goods_id', '=', $goods['goods_id'])->where('prop_str', '=', $goods['prop_str'])->fetch_one();
                    }

                    $ship_fee = 0;
                    if($is_first)
                    {
                        $ship_fee = $order['ship_fee'];
                    }

                    $data = array(
                        'trade_id'=>$trade[0],
                        'item_id'=>$goods['goods_id'],
                        'sku_id'=>$sku_id,
                        'cid'=>(int)$goods['cid'],
                        'title'=>$goods['goods_title'],
                        'price'=>$goods['price'],
                        'retail_price'=>$goods['original_price'],
                        'image_md5'=>$goods['image_md5'],
                        'protection_str'=>$shop['protections'],
                        'num'=>$goods['quantity'],
                        'seller_nick'=>$seller_nick,
                        'buyer_nick'=>$buyer_nick,
                        'props_str'=>$goods['prop_str'],
                        'refund_id'=>(int)$goods['refund_id'],
                        'refund_status'=>$goods['refund_status'],
                        'timeout_action_time'=>(int)$goods['timeout'],
                        'status'=>$goods['status']=='BUYER_PAYING'?'WAIT_BUYER_PAY':$goods['status'],
                        'coupon_name'=>$goods['promotion_name'],
                        'discount_fee'=>abs($goods['discount_fee']),
                        'adjust_fee'=>'-'.$goods['adjust_fee'],
                        'ship_fee'=>$ship_fee,
                        'total_fee'=>$goods['amount']+$goods['adjust_fee'],
                        'modified'=>(int)$goods['modified'],
                        'created'=>$goods['created'],
                    );

                    $insert = DB::insert('tc_order', array_keys($data))->values(array_values($data))->execute();

                    //更新parent_id
                    if($is_first){
                        $parent_id = $insert[0];
                    }
                    $update = array('parent_id' => $parent_id);
                    DB::update('tc_order')->set($update)->where('id','=',$insert[0])->execute();
                    $is_first = 0;

                    $this->create_snapshot($goods['goods_id'], $insert[0]);

                }


                //插入退款记录,客服介入，退款消息
                $refunds = DB::select()->from('refunds')->where('order_id', '=', $order['order_id'])->fetch_all();
                foreach($refunds as $refund){
                    $goods = DB::select()
                            ->from('tc_order')
                            ->where('trade_id', '=', $trade[0])
                            ->where('item_id', '=', $refund['goods_id'])
                            ->fetch_row();
                    
                    $data = array(
                        'trade_id'=>$trade[0],
                        'trade_sn'=>$order['order_sn'],
                        'order_id'=>$goods['id'],
                        'item_id'=>$refund['goods_id'],
                        'item_title'=>$goods['title'],
                        'price'=>$goods['price'],
                        'num'=>$goods['num'],
                        'buyer_nick'=>$buyer_nick,
                        'seller_nick'=>$seller_nick,
                        'shop_name'=>$shop['shop_name'],
                        'order_status'=>$goods['status'],
                        'status'=>$refund['status'],
                        'good_status'=>$refund['goods_status'],
                        'has_good_return'=>$refund['has_good_return'],
                        'total_fee'=>$refund['order_amount'],
                        'refund_fee'=>$refund['refund_amount'],
                        'payment'=>$refund['paymemt_amount'],
                        'reason'=>$refund['reason'],
                        'description'=>$refund['desc'],
                        'good_return_time'=>(int)$refund['good_return_time'],
                        'company_name'=>$refund['ship_company_name'],
                        'ship_no'=>$refund['ship_no'],
                        'address'=>$refund['address'].','.$refund['consignee'].','.$refund['phone'],
                        'refund_timeout'=>$refund['timeout'],
                        'modified'=>$refund['modified'],
                        'created'=>$refund['created'],
                    );

                    $result = DB::insert('tc_refund', array_keys($data))->values(array_values($data))->execute();
                    $new_refund_id = $result[0];

                    //插入退款消息
                    $refund_messages = DB::select()->from('refund_messages')->where('refund_id', '=', $refund['refund_id'])->fetch_all();
                    foreach($refund_messages as $message){
                        $data = array(
                            'refund_id'=>$new_refund_id,
                            'nickname'=>$message['owner_nick'],
                            'role'=>$message['owner_role'],
                            'content'=>$message['content'],
                            'image_md5'=>$message['image_md5'],
                            'created'=>$message['created'],
                        );
                        DB::insert('tc_refund_message', array_keys($data))->values(array_values($data))->execute();
                    }

                    //插入客服介入
                    if ($refund['involve_created']) {
                        $data = array(
                            'refund_id'=>$new_refund_id,
                            'contactor'=>$refund['involve_owner']==0?$buyer_nick:$seller_nick,
                            'mobile'=>$refund['involve_phone'],
                            'description'=>$refund['involve_desc'],
                            'created_by'=>$refund['involve_owner']==0?$buyer_nick:$seller_nick,
                            'refund_status'=>'SELLER_REFUSE_BUYER',
                            'created'=>$refund['involve_created'],

                        );
                        if ($refund['status'] == 'INVOLVE') {
                            //客服还未处理
                            $data['status'] = 'WAITING';
                        }
                        elseif ($refund['status'] == 'SUCCESS') {
                            //客服介入退款成功
                            $data['status'] = 'SUCCESS';
                            $data['operator'] = '超级管理员';
                            $data['deal_explain'] = '客服介入退款成功';
                            $data['dealed'] = (int)$refund['modified'];
                        }
                        elseif ($refund['status'] == 'CLOSED') {
                            //客服介入退款成功
                            $data['status'] = 'CLOSE';
                            $data['operator'] = '超级管理员';
                            $data['deal_explain'] = '客服介入退款关闭';
                            $data['dealed'] = (int)$refund['modified'];
                        }

                        DB::insert('tc_refund_involve', array_keys($data))->values(array_values($data))->execute();
                    }

                    //退款成功的，插入虚拟账户余额变更记录
                    if ($refund['status'] == 'SUCCESS') {
                        $data = array(
                            'account_id'=>$buyer_account_id,
                            'trade_id'=>$trade[0],
                            'refund_id'=>$new_refund_id,
                            'amount'=>$refund['paymemt_amount'],
                            'flag'=>1,
                            'type'=>'ORDER_REFUND',
                            'created'=>$refund['modified']?$refund['modified']:$refund['created'],
                        );
                        DB::insert('tc_account_detail', array_keys($data))->values(array_values($data))->execute();

                    }
                    
                }

                //插入店铺评价记录
                $shop_rates = DB::select()->from('shop_rates')->where('order_id', '=', $order['order_id'])->fetch_all();
                foreach($shop_rates as $shop_rate){
                    //判断存在
                    $is_exist = DB::select()
                            ->from('tc_shop_score')
                            ->where('shop_id', '=', $shop_rate['shop_id'])
                            ->where('trade_id', '=', $trade[0])
                            ->count_all();

                    if (!$is_exist) {
                        $data = array(
                            'shop_id'=>$shop_rate['shop_id'],
                            'trade_id'=>$trade[0],
                            'nick'=>$buyer_nick,
                            'des_score'=>$shop_rate['des_score'],
                            'service_score'=>$shop_rate['service_score'],
                            'express_score'=>$shop_rate['express_score'],
                            'created'=>$shop_rate['created_time'],
                        );
                        DB::insert('tc_shop_score', array_keys($data))->values(array_values($data))->execute();
                    }

                }

                //插入订单评价记录
                $order_rates = DB::select()->from('order_rates')->where('order_id', '=', $order['order_id'])->fetch_all();
                foreach($order_rates as $order_rate){
                    $goods = DB::select()
                            ->from('tc_order')
                            ->where('trade_id', '=', $trade[0])
                            ->where('item_id', '=', $order_rate['goods_id'])
                            ->fetch_row();
                    if ($order_rate['buyer_flag']) {
                        //买家评价
                        $data = array(
                            'trade_id'=>$trade[0],
                            'order_id'=>$goods['id'],
                            'role'=>0,
                            'nick'=>$buyer_nick,
                            'result'=>$order_rate['buyer_comment_score'],
                            'rated_nick'=>$seller_nick,
                            'item_id'=>$goods['item_id'],
                            'item_title'=>$goods['title'],
                            'item_price'=>$goods['price'],
                            'prop_str'=>$goods['props_str'],
                            'content'=>$order_rate['buyer_comment'],
                            'created'=>$order_rate['buyer_comment_time'],
                            'is_anonymity'=>$order_rate['is_anonymity'],
                            'deleted'=>$order_rate['buyer_deleted'],

                        );
                        DB::insert('tc_rate', array_keys($data))->values(array_values($data))->execute();

                    }

                    if ($order_rate['seller_flag']) {
                        //商家评价
                        $data = array(
                            'trade_id'=>$trade[0],
                            'order_id'=>$goods['id'],
                            'role'=>1,
                            'nick'=>$seller_nick,
                            'result'=>$order_rate['seller_comment_score'],
                            'rated_nick'=>$buyer_nick,
                            'item_id'=>$goods['item_id'],
                            'item_title'=>$goods['title'],
                            'item_price'=>$goods['price'],
                            'prop_str'=>$goods['props_str'],
                            'content'=>$order_rate['seller_comment'],
                            'created'=>$order_rate['seller_comment_time'],
                            'is_anonymity'=>$order_rate['is_anonymity'],
                            'deleted'=>$order_rate['seller_deleted'],

                        );
                        DB::insert('tc_rate', array_keys($data))->values(array_values($data))->execute();
                    }

                }

                $i++;
            }
            echo '>';
            $iterator->next();
        }
        cli::output("\n成功创建{$i}个已付款订单,忽略{$filter_count}个订单");
        return $this;
    }

    public function create_snapshot($goods_id, $order_id)
    {
        //插入tc_order_snapshot快照信息
        $goods_snapshot = DB::select()->from('goods')->where('goods_id','=', $goods_id)->fetch_row();
        if($goods_snapshot){
            $goods_snapshot['description'] = DB::select('description')->from('goods_fields')->where('goods_id','=', $goods_id)->fetch_one();
            $goods_snapshot = '[' . json_encode($goods_snapshot) . ']';
            $insert = array('order_id'=>$order_id,'snapshot'=>$goods_snapshot);
            DB::insert('tc_order_snapshot', array_keys($insert))->values(array_values($insert))->execute();
        }
        return $this;
    }

}